<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : !disabled ? '修改' : '查看'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataForm.type===1?dataRule1:dataRule3" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             inline label-width="100px">
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="dataForm.type" @change="getOrgNoList">
          <el-radio :label=1>普通店铺</el-radio>
          <el-radio :label=3>商圈</el-radio>
<!--          <el-radio :label=2>支行站点</el-radio>-->
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="dataForm.type === 2" label="支行对应" prop="orgNo">
        <el-select v-model="dataForm.orgNo" :disabled="disabled" clearable filterable placeholder="请选择"
                   class="width185">
          <el-option v-for="item in orgNoList"
                     :label="item.orgName"
                     :key="item.orgNo"
                     :value="item.orgNo">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item  label="分类" v-if="dataForm.type === 1" prop="shopCategoryId">
        <el-select v-model="dataForm.shopCategoryId" :disabled="disabled" clearable filterable placeholder="请选择"
                   class="width185">
          <el-option v-for="item in categoryList"
                     :label="item.name"
                     :key="item.id"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属商圈" v-if="dataForm.type === 1" prop="tradeAreaId">
        <el-select v-model="dataForm.tradeAreaId" :disabled="disabled" clearable filterable placeholder="请选择"
                   class="width185">
          <el-option
            v-for="shops in tradeAreas"
            :key="shops.id"
            :label="shops.name"
            :value="shops.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item  label="所属品牌" v-if="dataForm.type === 1" prop="brandId">
        <el-input v-model="dataForm.brandName" :disabled="disabled" placeholder="品牌名称">
          <el-button icon="el-icon-search" :disabled="disabled" slot="append" @click="clickeSelect" type="success" plain>选择</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="名字" prop="name">
        <el-input v-model="dataForm.name" :disabled="disabled" placeholder="店铺名字"></el-input>
      </el-form-item>
      <el-form-item label="简述" prop="introduction">
        <el-input v-model="dataForm.introduction" :disabled="disabled" placeholder="店铺简述"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type === 3" label="区域" prop="district">
        <el-dict code="DISTRICT" :disabled="disabled" v-model="dataForm.district"></el-dict>
      </el-form-item>
<!--      <el-form-item v-if="dataForm.type === 1" label="店铺标签" prop="tag">-->
<!--        <el-select v-model="dataForm.tag" :disabled="disabled" clearable filterable multiple placeholder="请选择"-->
<!--                   class="width185" @onChange="typeUpdata">-->
<!--          <el-option-->
<!--            v-for="tag in tags"-->
<!--            :key="tag.id"-->
<!--            :label="tag.name"-->
<!--            :value="tag.name">-->
<!--          </el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="营业时间" prop="workTime">
        <el-time-picker
          is-range
          value-format="H:mm"
          :disabled="disabled"
          v-model="dataForm.workTime"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="营业时间">
        </el-time-picker>
      </el-form-item>
<!--      <el-form-item label="营业状态" prop="business">-->
<!--        <el-dict code="IS_NOT" :disabled="disabled" v-model="dataForm.business"></el-dict>-->
<!--      </el-form-item>-->
      <el-form-item v-if="dataForm.type === 1" label="前台展示" prop="isOnSale">
        <el-dict code="IS_NOT" :disabled="disabled" v-model="dataForm.isOnSale"></el-dict>
      </el-form-item>
      <el-form-item v-if="dataForm.type === 1" label="热门店铺" prop="hot">
        <el-dict code="IS_NOT" :disabled="disabled" v-model="dataForm.hot"></el-dict>
      </el-form-item>
      <el-form-item v-if="dataForm.type === 1" label="店铺编码" prop="shopsSn">
        <el-input v-model="dataForm.shopsSn" :disabled="disabled" placeholder="店铺编码"></el-input>
      </el-form-item>
      <el-form-item label="图片" prop="imgUrl">
        <el-img v-model="dataForm.imgUrl" :disabled="disabled">
        </el-img>
      </el-form-item>
      <el-form-item v-if="dataForm.type === 3" label="图片(大)" prop="imgList">
        <el-img v-model="dataForm.imgList" :disabled="disabled">
        </el-img>
      </el-form-item>
<!--      <el-form-item label="店铺管理员" v-if="dataForm.type === 1" prop="userId">-->
<!--        <el-select v-model="dataForm.userId" :disabled="disabled" clearable filterable placeholder="请选择"-->
<!--                   class="width185">-->
<!--          <el-option-->
<!--            v-for="user in userList"-->
<!--            :key="user.userId"-->
<!--            :label="user.realName"-->
<!--            :value="user.userId">-->
<!--          </el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="查询经纬度" prop="longitude">
        <el-link href="https://lbs.qq.com/tool/getpoint/index.html" type="danger" :disabled="disabled" target="_blank">
          https://lbs.qq.com/tool/getpoint/index.html
        </el-link>
      </el-form-item><br>
      <el-form-item label="经纬度" prop="location">
        <el-input v-model="dataForm.location" :disabled="disabled" placeholder="经度"></el-input>
      </el-form-item>
<!--      <el-form-item label="经度" prop="longitude">-->
<!--        <el-input v-model="dataForm.longitude" :disabled="disabled" placeholder="经度"></el-input>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="纬度" prop="latitude">-->
<!--        <el-input v-model="dataForm.latitude" :disabled="disabled" placeholder="纬度"></el-input>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="是否总店" v-if="dataForm.type === 1" prop="level">-->
<!--        <el-select v-model="dataForm.level" :disabled="disabled" clearable filterable placeholder="请选择"-->
<!--                   class="width185">-->
<!--          <el-option-->
<!--            v-for="level in levels"-->
<!--            :key="level.id"-->
<!--            :label="level.name"-->
<!--            :value="level.id">-->
<!--          </el-option>-->
<!--        </el-select><br>-->
<!--        <span style="color:red">如果不为连锁店，需要设定一个总店，再设置一个分店，属于该总店</span>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="连锁店总店" v-if="dataForm.type === 1" prop="parentId">-->
<!--        <el-select v-model="dataForm.parentId" :disabled="disabled" clearable filterable placeholder="请选择"-->
<!--                   class="width185">-->
<!--          <el-option-->
<!--            v-for="shops in shopsList"-->
<!--            :key="shops.id"-->
<!--            :label="shops.name"-->
<!--            :value="shops.id">-->
<!--          </el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="详细位置" prop="details">
        <el-input v-model="dataForm.details" :disabled="disabled" placeholder="详细位置"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="telephone">
        <el-input v-model="dataForm.telephone" :disabled="disabled" placeholder="联系电话"></el-input>
      </el-form-item>
      <el-form-item v-show="dataForm.type === 1" label="描述" prop="shopDesc">
        <ueditor v-model="dataForm.shopDesc" :disabled="disabled" placeholder="描述"></ueditor>
      </el-form-item>
<!--      <el-form-item label="店铺公众号唯一id" prop="openid">-->
<!--        <el-input v-model="dataForm.openid" :disabled="disabled" placeholder="店铺公众号唯一id"></el-input>-->
<!--      </el-form-item>-->
      <el-form-item label="排序" prop="sort">
        <el-input v-model="dataForm.sort" :disabled="disabled" placeholder="排序"></el-input>
      </el-form-item>
      <el-form-item label="店铺评分" prop="shopScore">
        <el-input-number v-model="dataForm.shopScore" :precision="1" :min="1" :max="5" label="店铺评分"></el-input-number>
      </el-form-item>
      <el-form-item label="人均消费金额" prop="averagePrice">
        <el-input-number v-model="dataForm.averagePrice" :min="1" :max="99999" label="人均消费金额"></el-input-number>
      </el-form-item>
      <el-form-item label="营业执照" prop="businessPermit">
        <p style="text-align: center;float:left; padding: 5px;" v-for="(x,y) in formatImageList(dataForm.businessPermitImg)" :kye="y">
          <el-image :preview-src-list="[x]"  style="height: 200px;width: 200px"  :src="x" />
          <br>
          <el-button @click="delImageList(y)" type="text">删除</el-button>
        </p>
        <div style="padding: 20px;text-align: center;">

          <el-img
            v-show="(dataForm.businessPermitImg == null || dataForm.businessPermitImg.split(',').length<3)"
            :disabled="disabled"
            @input="getUrl"
            :showImg="false"
          >
          </el-img>

<!--          <el-button v-show="(dataForm.businessPermitImg == null || dataForm.businessPermitImg.split(',').length<3)"-->
<!--                     type="primary" @click="uploadHandle">上传文件</el-button>-->
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button v-if="!disabled" type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>

    <el-drawer
      :visible.sync="drawer"
      direction="rtl"
      :withHeader="false"
      :modal="false"
      size="60%">
      <div style="padding: 15px;overflow: auto;height: 100vh">
        <brand ref="brandRef" v-model="brand" @input="valueTransmit"></brand>
      </div>
    </el-drawer>


    <!-- 弹窗, 上传文件 -->
<!--    <upload v-if="uploadVisible" ref="upload" @url="getUrl"></upload>-->
  </el-dialog>
</template>

<script>
import brand from './brand'
import Upload from '../oss/oss-upload'

export default {
  data () {
    let locationRule = { validator: (rule, value, callback) => {
        if (value && value !== '') {
          let temp = value.replace(',',' ')
          temp = temp.split(' ')
          if(temp.length == 2){
            // 经纬度必须在固定值内
            if(Math.abs(temp[1] - 60) < 60 && Math.abs(temp[0] - 50) < 50){
              callback();
            }
          }
          callback(new Error('仅支持境内。请参考：28.236008,113.086002'));
        }
        callback();
      },
      trigger: 'blur'
    }
    return {
      brand: {},
      drawer: false,
      uploadVisible: false,
      ssq: '',
      selectedOptions: [],
      disabled: false,
      visible: false,
      shopCategoryList: [],
      orgNoList: [],
      categoryList: [],
      levels: [ {name: '总店', id: 1}, { name: '分店', id: 2 } ],
      dataForm: {
        id: '',
        name: '',
        openid: '',
        type: 1,
        shopCategoryId: '',
        shopCategoryName: '',
        shopsSn: '',
        imgUrl: '',
        imgList: '',
        userId: '',
        workTime: [new Date(), new Date()],
        // longitude: '',
        // latitude: '',
        location: '',
        details: '',
        telephone: '',
        orgNo: '',
        deleteStatus: '',
        shopDesc: '',
        sort: '',
        province: '',
        city: '',
        district: '',
        tag: '',
        isOnSale: '',
        chainStoe: '',
        parentId: '',
        level: 1,
        introduction: '',
        tradeAreaId: '',
        brandId: '',
        brandName:  '',
        shopScore: 5,
        averagePrice: 26,
        businessPermitImg: '',
        hot: 0
      },
      dataRule1: {
        name: [
          {
            required: true,
            message: '名称不能为空',
            trigger: 'blur'
          }
        ],
        shopDesc: [
          {
            required: true,
            message: '描述不能为空',
            trigger: 'blur'
          }
        ],
        location: [locationRule]
      },dataRule3: {
        location: [locationRule],
        name: [
          {
            required: true,
            message: '名称不能为空',
            trigger: 'blur'
          }
        ],
        district: [
          {
            required: true,
            message: '区域不能为空',
            trigger: 'blur'
          }
        ]
      },
      userList: JSON.parse(sessionStorage.getItem('userList') || '[]'),
      shopsList: [],
      tradeAreas: [],
      tags: []
    }
  },
  methods: {
    getUrl(url){
      if(url && url !== ''){
        var imageListisNull = this.dataForm.businessPermitImg === null || this.dataForm.businessPermitImg === undefined || this.dataForm.businessPermitImg === '';
        this.dataForm.businessPermitImg = (imageListisNull?"":this.dataForm.businessPermitImg+",")+url
      }
    },
    // 上传文件
    // uploadHandle () {
    //   this.uploadVisible = true
    //   this.$nextTick(() => {
    //     this.$refs.upload.init()
    //   })
    // },
    // 删除营业执照照片
    delImageList(index){
      let list = this.formatImageList(this.dataForm.businessPermitImg)
      if(list.length > 0){
        list.splice(index,1)
        this.dataForm.businessPermitImg = list.join()
      }
      console.log(this.dataForm.businessPermitImg == null || this.dataForm.businessPermitImg.split(',').length<6)
    },
    formatImageList(obj){
      if(obj != null && obj != ''){
        return obj.split(',')
      }
      return []
    },
    clickeSelect(){
      this.drawer = true
      this.$nextTick(() => {
        this.$refs.brandRef.getDataList();
      });
    },
    valueTransmit(v){
      this.dataForm.brandId = v.id
      this.dataForm.brandName = v.name
      this.drawer = false
    },
    init (id, disabled) {
      this.disabled = disabled
      this.dataForm.brandId = ''
      this.dataForm.brandName = ''
      this.dataForm.location = ''
      this.dataForm.id = id || ''
      this.visible = true
      this.selectedOptions = []
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: `/mall/shops/info/${this.dataForm.id}`,
            method: 'get'
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm = data.shops
              this.getOrgNoList(this.dataForm.type)
              if (data.shops.workTime) {
                this.dataForm.workTime = data.shops.workTime.split('-')
              }
            }
          })
        }
      })
      // this.getShopCategoryList()
      // this.getTagList()
      this.getCategoryList()
      // this.getShopsList()
      this.getTradeArea()
    },
    // getShopCategoryList () {
    //   this.$http({
    //     url: '/mall/shopscategory/queryAll',
    //     method: 'get',
    //     params: {
    //       'isShow': 1,
    //       'level': 2
    //     }
    //   }).then(({ data }) => {
    //     if (data && data.code === 0) {
    //       this.shopCategoryList = data.list
    //     } else {
    //       this.shopCategoryList = []
    //     }
    //   })
    // },
    getOrgNoList (value) {
      let orgNo = this.dataForm.orgNo
      if(1 === value){
        return
      }
      this.$http({
        url: '/sys/org/queryAll',
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.orgNoList = data.list
          this.dataForm.orgNo = orgNo
        } else {
          this.orgNoList = []
        }
      })
    },
    getCategoryList (value) {
      if(2 === value){
        return
      }
      this.$http({
        url: '/mall/shopscategory/queryAll',
        method: 'get',
        params: {
          'status': 1,
          'level': 2
        }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.categoryList = data.list
        } else {
          this.orgNoList = []
        }
      })
    },
    // getTagList () {
    //   this.$http({
    //     url: '/mall/tag/queryAll',
    //     method: 'get',
    //     params: {
    //       type: 0
    //     }
    //   }).then(({ data }) => {
    //     if (data && data.code === 0) {
    //       this.tags = data.list
    //     } else {
    //       this.tags = []
    //     }
    //   })
    // },
    getTradeArea () {
      this.$http({
        url: '/mall/shops/queryAll',
        method: 'get',
        params: {
          // level: 1,
          type: 3,
        }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.tradeAreas = data.list
        } else {
          this.tradeAreas = []
        }
      })
    },
    // getShopsList () {
    //   this.$http({
    //     url: '/mall/shops/queryAll',
    //     method: 'get',
    //     params: {
    //       level: 1,
    //       type: 1,
    //     }
    //   }).then(({ data }) => {
    //     if (data && data.code === 0) {
    //       this.shopsList = data.list
    //     } else {
    //       this.shopsList = []
    //     }
    //   })
    // },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm']
        .validate((valid) => {
          if (valid) {
            this.dataForm.level = this.dataForm.type === 3?1:2
            this.dataForm.location = this.dataForm.location.replace(',',' ')
            if(!this.dataForm.workTime || this.dataForm.workTime ===''){
              this.dataForm.workTime = ['8:00','22:00']
            }
            this.dataForm.workTime = this.dataForm.workTime[0] + '-' + this.dataForm.workTime[1]
            this.$http({
              url: `/mall/shops/${!this.dataForm.id ? 'save' : 'update'}`,
              method: 'post',
              data: this.dataForm
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          }
        })
    },
    typeUpdata () {
      this.$forceUpdate()
    }
  },
  components:{
    brand,
    Upload
  }
}
</script>
